var xhr = new XMLHttpRequest();
$(document).ready(function(){
	$('#tip').tipsy({
		opacity: 0.8,
		live: true,
		gravity: $.fn.tipsy.autoNS,
		fade: true
	});
	xhrJson();
});
	function xhrJson(){
		xhr.open("GET", "http://www.pelimaniaco.com/out/chrome",
				true);
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					if(xhr.responseText != false){
						var resp = JSON.parse(xhr.responseText);
						if(resp.status.code == 200){
							builView(resp);
						}
						else{
							$('#lateral_contenido').empty();
							$('#lateral_contenido').append('Sin resultados :S vuelve a intentalo').css({"color":"#4C8FFB","text-align":"center"});
						}
					}else{
						$('#lateral_contenido').empty();
						$('#lateral_contenido').append('<span style="display:block;">Hemos detectado que tu sesion de Pelimaniaco a caducado. Favor de Logearte nuevamente :D</span>').css({"color":"#DB4B39","text-align":"center"});
						$('#lateral_contenido').append('<a href="http://www.pelimaniaco.com/" id="login" target="_blank">Login</a>');
					}	
				} else {
					$('#lateral_contenido').empty();
					$('#lateral_contenido').append('Hubo un Problema con la conexion vuelve a intentarlo :D').css({"color":"#DB4B39","text-align":"center"});
				}
			}
		}
		xhr.send(null);
	}
	
	function builView(resp) {
		var publish = [];
		for(var i in resp.publications){
			if(resp.publications[i].type=='Pelicula'){
				publish.push('<a href="http://www.pelimaniaco.com/films~', resp.publications[i].id, '~', resp.publications[i].clean_title,'" target="_blank" >','<img src="',resp.publications[i].posters.big,'" id="tip" title="',resp.publications[i].title,'" width="100" height="113" />','</a>');
			}
			else if(resp.publications[i].type=='Serie'){
				publish.push('<a href="http://www.pelimaniaco.com/series~', resp.publications[i].id, '~', resp.publications[i].clean_title, '~', resp.publications[i].clean_title_episode, '" target="_blank" >','<img src="',resp.publications[i].posters.big,'" id="tip" title="',resp.publications[i].title, ' - ', resp.publications[i].title_episode,'" width="100" height="113" />','</a>');
			}
		}
		var html = publish.join('');
		$('#lateral_contenido').empty();
		$('#lateral_contenido').append(html);
		
	}
	
	function getCookie(cookieName) { 
		   var cookieValue=null, posValue, endPos,  
		   posName=document.cookie.indexOf(escape(cookieName)+'='); 
		   if (posName!=-1) { 
			   posValue=posName+(escape(cookieName)+'=').length; 
			   endPos=document.cookie.indexOf(';',posValue); 
			   if (endPos!=-1) cookieValue=unescape(document.cookie.substring(posValue,endPos)); 
			   else cookieValue=unescape(document.cookie.substring(posValue)); 
		   }
		   return cookieValue; 
	   }
	